﻿using System.Web.Mvc;
using QuestionsAnswers.UI.Models;

public class QuestionModelBinder : IModelBinder
{
    
    public object BindModel(ControllerContext controllerContext,
    ModelBindingContext bindingContext)
    {
        //see if there is an existing model to update and create one if not
        Question model = (Question)bindingContext.Model ??
        (Question)DependencyResolver.Current.GetService(typeof(Question));
        // find out if the value provider has the required prefix
        bool hasPrefix = bindingContext.ValueProvider  .ContainsPrefix(bindingContext.ModelName);
        string searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : "";
        // populate the fields of the model object
        model.QuestionId = int.Parse(GetValue(bindingContext, searchPrefix, "QuestionId"));
      
        model.Text = GetValue(bindingContext, searchPrefix, "Text");
        return model;
    }
    private string GetValue(ModelBindingContext context, string prefix, string key)
    {
        ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
        return vpr == null ? null : vpr.AttemptedValue;
    }
    private bool GetCheckedValue(ModelBindingContext context, string prefix, string key)
    {
        bool result = false;
        ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
        if (vpr != null)
        {
            result = (bool)vpr.ConvertTo(typeof(bool));
        }
        return result;
    }
}